package pers.karl.export.util;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class MysqlUtils {

    /**
     * 默认端口号
     */
    public static final int DEFAULT_PORT = 3306;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            log.error("mysql driver fail", e);
        }
    }

    /**
     * 连接默认端口的数据库
     * @param ip
     * @param user
     * @param password
     * @return
     * @throws SQLException
     */
    public static Connection getConnection(String ip, String user, String database, String password) throws SQLException {
        return getConnection(ip, DEFAULT_PORT, database, user, password);
    }

    /**
     * 获取连接
     *
     * @param ip
     * @param port
     * @param database
     * @param user
     * @param password
     * @return
     */
    public static Connection getConnection(String ip, int port, String database, String user, String password) throws SQLException {
        String url = String.format("jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=UTF-8&useSSL=false", ip, port, database);
        return SqlUtils.getConnection(url, user, password);
    }

}
